<?php 
session_start();
require_once ("class/m_receive.php");

	$m = new M_receive();
	
	if (isset($_POST['m'])  &&  $_POST['m']!=""){
		if ($_POST['m']== 'detail'){
			if(isset($_POST['id']) && $_POST['id']!=""){ 
				$id=$_POST['id'];
				//$id=1;
				$result_main =$m->getEditData($id);
				$result_detail=$m->getEditDataDetail($id);
				
				$rows=$result_detail->RecordCount();
				$h="";
				if ($rows>0){
					while($row = $result_detail->FetchRow()){
						$h.="<tr>".getProductTableDetail($row)."</tr>"; 
					}
				}
				$re=array('header'=>json_encode($result_main),
						'html'=>$h,
						'rows'=>$rows
						);
						
				echo json_encode($re);
			}else{
				echo "Errro";
			}
			
		//******************************
		//****       Product Detail
		//******************************			
		}else if ($_POST['m']== 'p_detail'){
			if(isset($_POST['id']) && $_POST['id']!=""){ 
				$id=$_POST['id'];
				$amt=$_POST['amt'];
				$price=$_POST['price'];
				//$id=1;
				$row=$m->getProductDetail($id,$amt,$price);
				
				echo "<tr>".getProductTableDetail($row)."</tr>"; //json_encode($m->getProductDetail($id,$amt));
			}else{
				echo "Errro";
			}
			
		//******************************
		//****       Add
		//******************************					
		}else if ($_POST['m']== 'add'){
			$ar= $_POST['var'];
			
			//$ar['Total']=$_POST['total'];
			
			$ar["CreatedBy"]=$_SESSION['username'];
			$ar["CreatedDate"]=date( "Y/m/d H:i:s" );
			
			$id=$m->InsertData($ar);
			//echo $id;
			$list=$ar['Detail'];
			$sql="Insert Into tb_receive_product_detail (Receive, Product, Amount_rq, Price	, Total) values ";
			$sqlDetail = "";
			
			 foreach ($list as $key => $val) {
					//_r($list[$key]. ' ');
				$sqlDetail.=",(".$id.",".$key.",".$list[$key]['amt'].",".$list[$key]['price'].",". $list[$key]['amt']*$list[$key]['price']  ." ) ";
			 }
			//remove first comma
			$sqlDetail = substr($sqlDetail,1);
			//Excute
			$m->Excute($sql.$sqlDetail);					 
			//echo $sqlDetail ; 
			echo "<tr>".getTable($m->getDataDetail($id),$_POST['rows']+1)."</tr>"; 
			
		}else if ($_POST['m']=='running'){
				$no=  $m->getRunning();
				echo "RE_".date( "ymd" ).str_repeat('0', 3-strlen($no) ).$no;

		//******************************
		//****       Edit
		//******************************					
		}else if ($_POST['m']=='edit'){
			if (isset($_POST['var'])){
				$ar=$_POST['var'];
				$flag=isset($ar);
				$id=$_POST['id'];
				//$ar['Total']=$_POST['total'];
				$ar["UpdatedBy"]=$_SESSION['username'];
				$ar["UpdatedDate"]=date( "Y/m/d H:i:s" );
				
				$list=$ar['Detail'];
				
				$sqlScript="select * from tb_receive_product where ID='".$id."'";
			
				// Insert data
				$m->updateData($sqlScript, $ar);
				
				// clear data
				$m->delDataDetail( $id );
				
				$sql="Insert Into tb_receive_product_detail (Receive, Product, Amount_rq, Price	, Total) values ";
							
				 foreach ($list as $key => $val) {
					//($list[$key]. ' ');
					$sqlDetail.=",(".$id.",".$key.",".$list[$key]['amt'].",".$list[$key]['price'].",". $list[$key]['amt']*$list[$key]['price']  ." ) ";
				 }
				//remove first comma
				$sqlDetail = substr($sqlDetail,1);
				//Excute
				$m->Excute($sql.$sqlDetail);	
			
				echo  getTable($m->getDataDetail($id),$_POST['rows']);
			}
		//******************************
		//****       Delete
		//******************************					
		}else if ($_POST['m']=='del'){
			if(isset($_POST['var'])){
				$o=$_POST['var'];
				$m->delData($o["id"],$_SESSION['username']);
			}
		//******************************
		//****       View
		//******************************
		}else if ($_POST['m']== 'view'){
			$id=$_POST['id'];
			$page=$_POST['page'];
			$type=$_POST['type'];
			
			$page=isset($page)?$page:1;
			
			$resultHeader=$m->getDataDetail($id);
			
			$result=$m->ReceiveViewDetail($id,$page,$type);
						
			$rows=$m->getRowCount();
			$i=1 + (($page-1) * $m->getListPage());
			$html="";
			if ($rows>0){
				while($row = $result->FetchRow()){
					If($i%2 <> 0){
						$html .= "<tr class=row1>";
					} else{
						$html .= "<tr>";    
					}
					$html .= getTableView($row,$i,$type)."</tr>";
					$i++;
				}
			}else{
					$html="<tr>"
					."<td colspan='9' align='center' ><img src='./images/info.gif'/><b/></td>"
					."</tr>";
			}
			//Return result , rows , page
			$ar_result=array('data'=>$html,
							'header'=> json_encode($resultHeader),
							'rows'=>$rows,
							'totalpage'=>$m->getTotalPage());
			echo json_encode( $ar_result );
			
		//******************************
		//****       update after checking
		//******************************			
		}else if ($_POST['m']== 'add_rc'){
			if(isset($_POST['id'])){
				$id=$_POST['id'];
				$total=$_POST['total'];
				$branch=$_SESSION['bid'];
				$list= $_POST['var'];//Array {id:xx, 'pdid':01, 'amt':001,'cost':100}
				$ar_count=count($list);
				$user=$_SESSION['username'];
			
				//loop update
				 foreach ($list as $val) {
					
					$m->UpdateReceiveProduct($val['id'],$val['amt']);
					
					$m->UpdateStock($val['pdid'],$branch,$val['amt'],$user);
					
					$m->updateCostPrice($val['pdid'] ,$val['cost']);
				 }
				 //Change Status
				$sqlupdate="Update tb_receive_product "
								." set Status=1 "
								.", Total =".$total
								.", ReceivedDate=Now() "
								.", ReceivedBy='".$user."'"
								." Where ID=".$id;					 
				
				 $m->Excute($sqlupdate);
				 
				echo "completed";
			}else 
				echo "error";
		//******************************
		//****       Search
		//******************************
		}else if ($_POST['m']== 'search'){
			$code=$_POST['code'];
			$supplierid=$_POST['supplierid'];
			$receivedatefrom=$_POST['receivedatefrom'];
			$receivedateto=$_POST['receivedateto'];
			$status=$_POST['status'];
			
			$page=$_POST['page'];
			
			$page=isset($page)?$page:1;
			
			$result=$m->getData($code,$supplierid,$receivedatefrom,$receivedateto,$status,$page);
			$rows=$m->getRowCount();
			$i=1 + (($page-1) * $m->getListPage());
			$html="";
			
			if($rows>0){
				while($row = $result->FetchRow()){
					if ($row['flag'] != '0' && $row['Status']=='Closed'){
						$style="style='color:red'";
					}else{
							$style="";
					}
					
					If($i%2 <> 0){
						$html .= "<tr class=row1 ".$style.">";
					} else{
						$html .= "<tr ".$style.">";    
					}
					$html .= getTable($row,$i)."</tr>";
					$i++;
				}
			}else{
				$html="<tr>"
					."<td colspan='12' align='center' ><img src='./images/info.gif'/><b/></td>"
					."</tr>";
			}
			//Return result , rows , page
			$ar_result=array('data'=>$html,
							'rows'=>$rows,
							'totalpage'=>$m->getTotalPage());
			echo json_encode( $ar_result );
		}
		
	//******************************
	//****       Get combo data
	//******************************			
	}else{
		if (isset($_GET['c']) && $_GET['c'] !="" ){
			echo json_encode( $m->getDataCBO($_GET['c']));
		}		
	}
	
	function getProductTableDetail($arr){
			$html= "<td align='right'>".$arr["ID"]."</td>"
					."<td align='left' style='padding-left:3px'>".$arr["ProductName"] ."</td>"
					."<td align='center'>".$arr["Unit"]."</td>"
					."<td align='right'>".number_format($arr["Amount"],0,'.',',')."</td>"
					."<td align='right'>".number_format($arr["Price"],2,'.',','). "</td>"
					."<td align='right'>".number_format($arr["Total"],2,'.',',')."</td>"
					."<td align='center'><img src='images/remove16.png' style='cursor:hand' id='btnRemove' border=0/></td>";
			return $html;
	}
	//for view 
	function getTableView($row,$i,$type){
	
		$html .="<td align='right'>".$i."</td>";
		$html .="<td style='display:none'>".$row['ID']."</td>";
		$html .="<td style='display:none'>".$row['ProductID']."</td>";
		$html .="<td align='left'>".$row['ProductName']."</td>";
		$html .="<td align='left'>".$row['CatName']."</td>";
		$html .="<td align='center'>".$row['ProductType']."</td>";
		$html .="<td align='center'>".$row['Unit']."</td>";
		$html .="<td align='right'>".number_format($row['Amount_rq'],0,'.',',')."</td>";
		//Type is view details
		if ($type=='d'){
			$html .="<td  align='right'>".number_format($row['Amount_rc'],0,'.',',')."</td>";
		}else{
			$html .="<td  align='center'><input type='text'  style='text-align:right;border:1px solid #ccc' class='amt_rc' name='amt_rc' maxlength='5' size='5' value=".$row['Amount_rq']."></input></td>";
		}
		
		$html .="<td  align='right'>".number_format($row['Price'],2,'.',',')."</td>";
		$html .="<td  align='right'>".number_format($row['Total'],2,'.',',')."</td>";
		
		return $html;
	}
	//for search
	function getTable($row,$i){
	global $receiveScreen;
		if ($row["Status"]=='Check'){
			$check="<img src='./images/receive.png' class='btnReceive' style='cursor:pointer'  title='Check Product' border='0'/>";
			$iStatus="<font style='font-weight:bold;color:green'>".$row["Status"]."</font>";
			
			if ($_SESSION["permission"][$receiveScreen]['Edit']=='1') 	
				$edit="<img src='./images/edit.png' class='btnEdit' style='cursor:pointer'  title='Edit' border='0'/>";
			else 
				$edit="";
				
			if ($_SESSION["permission"][$receiveScreen]['Deleted']=='1') 	
				$delete="<img src='./images/remove.png' class='btnDel' style='cursor:pointer'  title='Delete' border='0'/>";
			else 
				$delete="";
		}else{
			$check="<img src='./images/view.png' class='btnView' style='cursor:pointer'  title='View Product' border='0'/>";
			$iStatus="<font style='font-weight:bold;color:#666'>".$row["Status"]."</font>";			
			$edit="&nbsp;";
			$delete="&nbsp;";
		}
		$ReceiveDate = $row['ReceivedDate']=='' || $row['ReceivedDate']=='-'?'&nbsp;':$row['ReceivedDate'] .' by <b>' . $row['ReceivedBy'].'<b>';
		
		$html .="<td align='right'>".$i."</td>";
		$html .="<td style='display:none'>".$row['ID']."</td>";
		$html .="<td align='left'>".$row['Code']."</td>";
		$html .="<td align='left'>".$row['SupplierName']."</td>";
		$html .="<td align='center'>".$ReceiveDate."</td>";
		$html .="<td align='right'>".$row['CreditTerm']."</td>";
		$html .="<td align='center'>".$iStatus."</td>";
		// $html .="<td align='right'>".number_format($row['Amount'],0) ."</td>";
		$html .="<td align='right'>".number_format( $row['Total'] ,2,'.',',' )."</td>";
		$html .="<td align='center'>".$check."</td>";		
		// $html .="<td align='center'><img src='./images/view.png' class='btnView' style='cursor:pointer'  title='View' border='0'/></td>";
		$html .="<td align='center'>".$edit."</td>";
		$html .="<td align='center'>".$delete."</td>";
		
		return $html;
	}

?>